package cn.jit.ssm.utils;

import cn.jit.ssm.constant.SessionKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.Serializable;
import java.util.Random;

/**
 * 生成验证码
 *
 * @author: Cecurio
 * @create: 2017-12-07 17:27
 **/
public class RandomValidateCodeUtil implements Serializable {
    public static final Logger logger = LoggerFactory.getLogger(RandomValidateCodeUtil.class);

    private static final long serialVersionUID = 1L;

    public static final String RANDOM_CODE_KEY = "RANDOMVALIDATECODEKEY";
    private static Random random = new Random();
    private static String randString = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuxwxyz";//随机产生的字符串

    private static int width = 70; //图片宽
    private static int height = 30; //图片高
    private static int lineSize = 40; //干扰线数量
    private static int stringNum = 4; //随机产生字符数

    private static Font getFont() {
        return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
    }

    /**
     * 随机获取颜色
     * @param fc
     * @param bc
     * @return
     */
    private static Color getRandomColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc - 16);
        int g = fc + random.nextInt(bc - fc - 14);
        int b = fc + random.nextInt(bc - fc - 18);
        return new Color(r, g, b);
    }

    /**
     *
     * @param num
     * @return
     */
    public static String getRandomString(int num) {
        return String.valueOf(randString.charAt(num));
    }

    private static String drawString(Graphics g, String randomString, int i) {
        g.setFont(getFont());
        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));
        String rand = String.valueOf(getRandomString(random.nextInt(randString.length())));
        randomString += rand;
        g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, 15 * (i - 1) + 4, 16);
        return randomString;
    }

    /**
     * 在图形中画干扰线
     * @param g
     */
    private static void drawLine(Graphics g) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        // drawLine(int x1, int y1, int x2, int y2)
        // 在图形上下文坐标系中的点（x1，y1）和（x2，y2）之间绘制一条使用当前颜色的线
        g.drawLine(x, y, x + random.nextInt(13), y + random.nextInt(15));
    }

    /**
     * 生成验证码，并以流的形式响应给response
     * @param request HttpServletRequest对象
     * @param response HttpServletResponse对象
     */
    public static void getRandomcode(HttpServletRequest request, HttpServletResponse response) {
        // 获取Session，把生成的验证码存在session里
        HttpSession session = request.getSession();

        //设置页面不缓存
        response.setHeader("pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        // 产生Image对象的Graphics对象,该对象可以在图像上进行各种绘制操作
        Graphics g = image.getGraphics();
        // Fills the specified rectangle.
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
        g.setColor(getRandomColor(110, 133));

        for (int i = 0; i <= lineSize; ++i) {
            drawLine(g);
        }

        String randomString = "";
        for (int i = 1; i <= stringNum; i++) {
            randomString = drawString(g, randomString, i);
        }

        session.removeAttribute(RANDOM_CODE_KEY);
        session.setAttribute(RANDOM_CODE_KEY, randomString);
        session.setAttribute(SessionKey.VALIDATE_CODE, randomString);
        logger.info("生成的验证码是==> " + randomString);
        // 处理此图形上下文并释放它正在使用的任何系统资源
        g.dispose();

        try {
            // 将图片以流的形式响应
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
